package com.app.car.usb;

import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.app.car.R;
import com.app.car.basis.Constants;
import com.app.car.home.HomeBaseActivity;
import com.github.mjdev.libaums.UsbMassStorageDevice;
import com.github.mjdev.libaums.fs.UsbFile;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;

import butterknife.BindView;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;
import my.DialogUtils;
import my.FileUtils;

/**
 * usb界面
 */
public class UsbIndexActivity extends HomeBaseActivity implements USBBroadCastReceiver.UsbListener{


    @BindView(R.id.tv_progress)
    TextView showProgressTv;

    @BindView(R.id.lv_usb)
    ListView usbLv;

    @BindView(R.id.lv_local)
    ListView localLv;

    //本地文件列表相关
    private ArrayList<File> localList;
    private FileListAdapter<File> localAdapter;
    private String localRootPath = Constants.DIR_EXCEL;
    private String localCurrentPath = "";
    //USB文件列表相关
    private ArrayList<UsbFile> usbList;
    private FileListAdapter<UsbFile> usbAdapter;
    private UsbHelper usbHelper;

    @Override
    public void refresh() {
        super.refresh();
        openLocalFile(new File(localCurrentPath));
    }

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.usb_index_activity);
        initLocalFile();
        initUsbFile();
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
    }

    @OnClick({R.id.icon_local_back, R.id.icon_usb_back})
    public void btnClick(View v) {
        switch (v.getId()) {
            case R.id.icon_local_back:
                if (!localCurrentPath.equals(localRootPath)) {
                    //不是根目录，返回上一目录
                    openLocalFile(new File(localCurrentPath).getParentFile());
                }
                break;
            case R.id.icon_usb_back:
                if (usbHelper.getParentFolder() != null) {
                    //不是根目录，返回上一目录
                    openUsbFile(usbHelper.getParentFolder()
                    );
                }
                break;
        }
    }



    /**
     * 初始化本地文件列表
     */
    private void initLocalFile() {
        localList = new ArrayList<>();

        File file = new File(localRootPath);
        if (!file.exists()) {
            file.mkdirs();
        }

        Collections.addAll(localList, file.listFiles());
        localCurrentPath = localRootPath;
        localAdapter = new FileListAdapter<>(this, localList);
        localLv.setAdapter(localAdapter);
        localLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                openLocalFile(localList.get(position));
            }
        });
        localLv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                DialogUtils.showWarningDialog(mContext, "是否删除文件？", "确定", new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        FileUtils.deleteFile(localList.get(position));
                        openLocalFile(new File(localCurrentPath));
                    }
                });
                return true;
            }
        });
    }

    /**
     * 初始化 USB文件列表
     */
    private void initUsbFile() {
        usbHelper = new UsbHelper(this, this);
        usbList = new ArrayList<>();
        usbAdapter = new FileListAdapter<>(this, usbList);
        usbLv.setAdapter(usbAdapter);
        usbLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                UsbFile file = usbList.get(position);
                openUsbFile(file);
            }
        });
        updateUsbFile(0);
    }


    /**
     * 打开 USB File
     *
     * @param file USB File
     */
    private void openUsbFile(UsbFile file) {
        if (file.isDirectory()) {
            //文件夹更新列表
            usbList.clear();
            usbList.addAll(usbHelper.getUsbFolderFileList(file));
            usbAdapter.notifyDataSetChanged();
        } else {
            //开启线程，将文件复制到本地
            copyUSbFile(file);
        }
    }

    /**
     * 复制 USB 文件到本地
     *
     * @param file USB文件
     */
    private void copyUSbFile(final UsbFile file) {
        //复制到本地的文件路径
        final String filePath = localCurrentPath + File.separator + file.getName();
        new Thread(new Runnable() {
            @Override
            public void run() {
                //复制结果
                final boolean result = usbHelper.saveUSbFileToLocal(file, filePath, new UsbHelper.DownloadProgressListener() {
                    @Override
                    public void downloadProgress(final int progress) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                String text = "从U盘复制到本地 : "
                                        + "\n进度 : " + progress;
                                showProgressTv.setText(text);
                            }
                        });
                    }
                });
                //主线程更新UI
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (result) {
                            openLocalFile(new File(localCurrentPath));
                        } else {
                            showToast("复制失败");
                        }
                    }
                });
            }
        }).start();
    }

    /**
     * 打开本地 File
     *
     * @param file File
     */
    private void openLocalFile(File file) {
        if (file.isDirectory()) {
            //文件夹更新列表
            localList.clear();
            Collections.addAll(localList, file.listFiles());
            localAdapter.notifyDataSetChanged();
            localCurrentPath = file.getAbsolutePath();
        } else {
            //开启线程，将文件复制到本地
            copyLocalFile(file);
        }
    }

    /**
     * 复制 USB 文件到本地
     *
     * @param file USB文件
     */
    private void copyLocalFile(final File file) {
        //复制到本地的文件路径
        new Thread(new Runnable() {
            @Override
            public void run() {
                //复制结果
                final boolean result = usbHelper.saveSDFileToUsb(file, usbHelper.getCurrentFolder(), new UsbHelper.DownloadProgressListener() {
                    @Override
                    public void downloadProgress(final int progress) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                String text = "从本地复制到U盘 : "
                                        + "\n进度 : " + progress;
                                showProgressTv.setText(text);
                            }
                        });
                    }
                });
                //主线程更新UI
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (result) {
                            openUsbFile(usbHelper.getCurrentFolder());
                        } else {
                        showToast("复制失败");
                        }
                    }
                });
            }
        }).start();
    }

    /**
     * 更新 USB 文件列表
     */
    private void updateUsbFile(int position) {
        UsbMassStorageDevice[] usbMassStorageDevices = usbHelper.getDeviceList();
        if (usbMassStorageDevices.length > 0) {
            //存在USB
            usbList.clear();
            usbList.addAll(usbHelper.readDevice(usbMassStorageDevices[position]));
            usbAdapter.notifyDataSetChanged();
        } else {
            Log.e("UsbTestActivity", "No Usb Device");
            usbList.clear();
            usbAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void insertUsb(UsbDevice device_add) {
        if (usbList.size() == 0) {
            updateUsbFile(0);
        }
    }

    @Override
    public void removeUsb(UsbDevice device_remove) {
        updateUsbFile(0);
    }

    @Override
    public void getReadUsbPermission(UsbDevice usbDevice) {

    }

    @Override
    public void failedReadUsb(UsbDevice usbDevice) {

    }
    @Override
    protected void onDestroy() {
        usbHelper.finishUsbHelper();
        super.onDestroy();
    }
}